package com.cuotigou.service.impl;

import com.cuotigou.config.ConfigUtils;
import com.cuotigou.mapper.*;
import com.cuotigou.pojo.*;
import com.cuotigou.service.OfferRewardService;
import com.cuotigou.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Created by Administrator on 2018/11/7.
 */
@Service
@Transactional
public class OfferRewardServiceImpl implements OfferRewardService {

    private static final Logger log = LoggerFactory.getLogger(OfferRewardServiceImpl.class);

    @Autowired
    private SOfferRewardMapper sOfferRewardMapper;
    @Autowired
    private SOfferRewardAnswerMapper sOfferRewardAnswerMapper;
    @Autowired
    private SOfferRewardLabelMapper sOfferRewardLabelMapper;
    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SLabelMapper sLabelMapper;
    @Autowired
    private SSubjectMapper sSubjectMapper;
    @Autowired
    private SWrongTopicMapper sWrongTopicMapper;
    @Autowired
    private SUserToWrongTopicMapper sUserToWrongTopicMapper;
    @Autowired
    private SOfferRewardAnswerFabulousMapper sOfferRewardAnswerFabulousMapper;
    @Autowired
    private SConfigMapper sConfigMapper;
    @Autowired
    private SWrongTopicLabelMapper sWrongTopicLabelMapper;


    @Override
    public ObjectResult index(XMLBean xmlBean) {
        List<SOfferReward> sOfferRewards = new ArrayList<>();
        // 0 未解决 1已解决 2 热门悬赏
        Map<String, Object> map = new HashMap<>();

        map.put("status", xmlBean.getStatus());
        map.put("isHot",xmlBean.getIsHot());
        if (StringUtil.isEmpty(xmlBean.getTitle())) {
            map.put("title", null);
        } else {
            map.put("title", "%" + xmlBean.getTitle() + "%");
        }
        if(!StringUtil.isEmpty(xmlBean.getId())){
            map.put("gradeId", Integer.parseInt(xmlBean.getId()));
        }else if (!StringUtil.isEmpty(xmlBean.getToken())){
            String userId = CommonUtils.decToken(xmlBean.getToken());
            SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));
            map.put("gradeId", sUser.getGradeId());
        }
        if (!"全部".equals(xmlBean.getSubject())) {
            map.put("subject", xmlBean.getSubject());
        }
        sOfferRewards = sOfferRewardMapper.selectOfferRewardByStatus(map);


        Page<SOfferReward> page = new Page<>();
        page.setP(xmlBean.getP() == null ? 1 : Integer.parseInt(xmlBean.getP()));
        List<SOfferReward> pageContent = page.getPageContent(sOfferRewards);
        for (SOfferReward sOfferReward : pageContent) {
            //悬赏标签
            List<String> list = sOfferRewardLabelMapper.select(sOfferReward.getId());
            sOfferReward.setLabelList(list);
            //图片数组

            if (sOfferReward.getImage()!= null /*&& sOfferReward.getImage().contains(",")*/) {
                String[] split = sOfferReward.getImage().split(",");
                if (split.length > 3) {
                    String[] arrays = {split[0],split[1],split[2]};
                    sOfferReward.setImageList(arrays);
                } else {
                    sOfferReward.setImageList(split);
                }
            }else {
                String[] strings = {};
                sOfferReward.setImageList(strings);
            }

        }

        map.clear();

        map.put("isSee",0);
        //是否有未读回答
        if(!StringUtil.isEmpty(xmlBean.getToken())){
            String userId = CommonUtils.decToken(xmlBean.getToken());
            Integer count = sOfferRewardMapper.selecIsSee(Integer.parseInt(userId));
            if (count>0) {
                map.put("isSee", 1);
            }
        }

        map.put("list", pageContent);
        map.put("count", page.getPageTotal());

        return ObjectResult.build("1", "成功", map);
    }

    @Override
    public ObjectResult offerRewardRelease(XMLBean xmlBean,MultipartFile[] files) {
        String userId = CommonUtils.decToken(xmlBean.getToken());


        SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

        if (xmlBean.getIntegral() < sUser.getIntegral()) {
            ObjectResult.build("0", "积分不足");
        }

        try {
            SOfferReward sOfferReward = new SOfferReward();
            sOfferReward.setUserId(Long.parseLong(userId));
            sOfferReward.setTitle(xmlBean.getTitle());//标题
            sOfferReward.setContent(xmlBean.getContent());//内容
            sOfferReward.setGradeId(sUser.getGradeId());//年级id
            sOfferReward.setIntegral(xmlBean.getIntegral());//积分
            sOfferReward.setStatus(0);
            sOfferReward.setAddTime(new Date());
            sOfferReward.setModifyTime(new Date());

            //科目id
            Map<String, Object> map = new HashMap<>();
            map.put("gradeId", sUser.getGradeId());
            map.put("labelId", xmlBean.getId());
            sOfferReward.setSubjectId(sSubjectMapper.selectSubjectId(map));

            //图片
            if (files.length>0) {
                StringBuilder builder = new StringBuilder();
                List<String> list = FileUtil.upload(files, ConfigUtils.OFFERRWARD_URL);
                int i = 1;
                for (String strings :list){
                    if (i == list.size() ) {
                        builder.append(ConfigUtils.FILE_URL + "image/offereward/" + strings);
                    } else {
                        builder.append(ConfigUtils.FILE_URL + "image/offereward/" + strings).append(",");
                    }
                    i++;
                }
                sOfferReward.setImage(builder.toString());
            }

            //添加悬赏
            sOfferRewardMapper.insertSelective(sOfferReward);

            //悬赏标签
            if (!StringUtil.isEmpty(xmlBean.getLabel())) {
                String[] split = xmlBean.getLabel().split(",");
                for (int i = 0; i < split.length; i++) {
                    SOfferRewardLabel sOfferRewardLabel = new SOfferRewardLabel();
                    sOfferRewardLabel.setLabelId(Long.parseLong(split[i]));
                    sOfferRewardLabel.setRewadId(sOfferReward.getId());
                    sOfferRewardLabelMapper.insertSelective(sOfferRewardLabel);
                }
            }
            //年级标签
            Long id = sLabelMapper.selectId(sUser.getGradeId());
            SOfferRewardLabel sOfferRewardLabel = new SOfferRewardLabel();
            sOfferRewardLabel.setLabelId(id);
            sOfferRewardLabel.setRewadId(sOfferReward.getId());
            sOfferRewardLabelMapper.insertSelective(sOfferRewardLabel);

        } catch (RuntimeException e) {
            ExceptionUtil.logError(e, log);
            return ObjectResult.build("0", "发布失败");
        }

        return ObjectResult.build("1", "发布成功");
    }

    @Override
    public ObjectResult offerRewardDelete(XMLBean xmlBean) {
        String[] split = xmlBean.getId().split(",");

        for (int i = 0; i < split.length; i++) {
            SOfferReward sOfferReward = new SOfferReward();
            sOfferReward.setId(Long.parseLong(split[i]));
            sOfferReward.setIsDelete(1);
            sOfferReward.setModifyTime(new Date());

            sOfferRewardMapper.updateByPrimaryKeySelective(sOfferReward);
        }

        return ObjectResult.build("1", "删除悬赏成功");
    }

    @Override
    public ObjectResult offerRewardUpdate(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SOfferReward sOfferReward = sOfferRewardMapper
                .selectByPrimaryKey(Long.parseLong(xmlBean.getId()));
        try {
            if (!userId.equals(sOfferReward.getUserId().toString())){
                return ObjectResult.build("0","非悬赏发布人");
            }
            sOfferReward.setIntegral(xmlBean.getIntegral());
            sOfferRewardMapper.updateByPrimaryKeySelective(sOfferReward);
        }catch (RuntimeException e){
            return ObjectResult.build("0","修改悬赏失败");
        }
        return ObjectResult.build("1","修改悬赏成功");
    }

    @Override
    public ObjectResult myOfferReward(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        List<SOfferReward> sOfferRewards = sOfferRewardMapper.selectOfferRewardListByUserId(Long.parseLong(userId));
        Page<SOfferReward> page = new Page<>();
        page.setP(xmlBean.getP() == null ? 1 : Integer.parseInt(xmlBean.getP()));
        List<SOfferReward> content = page.getPageContent(sOfferRewards);

        for (SOfferReward sOfferReward:content){
            Integer count = sOfferRewardMapper.selecOfferRewardIsSee(sOfferReward.getId());
            if (count>0){
                sOfferReward.setIsSee(1);
            }else {
                sOfferReward.setIsSee(0);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("count", page.getPageTotal());
        map.put("list", content);

        return ObjectResult.build("1", "成功", map);
    }

    @Override
    public ObjectResult offerRewardDetails(XMLBean xmlBean) {

        SOfferReward sOfferReward = sOfferRewardMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getId()));
        //悬赏标签
        sOfferReward.setLabelList(sOfferRewardLabelMapper.select(sOfferReward.getId()));
        //图片数组
        if (sOfferReward.getImage() != null && sOfferReward.getImage().contains(",")) {
            sOfferReward.setImageList(sOfferReward.getImage().split(","));
        } else if (StringUtil.isEmpty(sOfferReward.getImage())) {
            String[] strings = {};
            sOfferReward.setImageList(strings);
        } else {
            String[] strings = {sOfferReward.getImage()};
            sOfferReward.setImageList(strings);
        }

        //悬赏回答列表
        List<SOfferRewardAnswer> sOfferRewardAnswers = sOfferRewardAnswerMapper.selectofferRewardAnswer(xmlBean.getId());
        //分页
        Page<SOfferRewardAnswer> page = new Page<>();
        page.setP(xmlBean.getP() == null ? 1 : Integer.parseInt(xmlBean.getP()));
        page.setPageSize(10);
        List<SOfferRewardAnswer> list = page.getPageContent(sOfferRewardAnswers);

        Map<String, Object> map = new HashMap<>();

        Integer isAdd = 0;//是否已加入错题本
        if(!StringUtil.isEmpty(xmlBean.getToken())){
            String userId = CommonUtils.decToken(xmlBean.getToken());
            map.put("userId",userId);
            map.put("rewadId",xmlBean.getId());
            isAdd = sWrongTopicMapper.selectWrongTopicCountByMap(map);

            for (SOfferRewardAnswer sOfferRewardAnswer : list) {
                //评论时间为多少时间前
                sOfferRewardAnswer.setTime(RelativeDateFormat.format(sOfferRewardAnswer.getAddTime()));
                //是否点赞和举报
                SOfferRewardAnswerFabulous sOfferRewardAnswerFabulous = new SOfferRewardAnswerFabulous();
                sOfferRewardAnswerFabulous.setUserId(Long.parseLong(userId));
                sOfferRewardAnswerFabulous.setAnswerId(sOfferRewardAnswer.getId());
                SOfferRewardAnswerFabulous select = sOfferRewardAnswerFabulousMapper
                        .select(sOfferRewardAnswerFabulous);
                if(select != null){
                    sOfferRewardAnswer.setIsReport(select.getIsReport());
                    sOfferRewardAnswer.setIsFabulous(select.getIsFabulous());
                }
                //评论图片
                if (!StringUtil.isEmpty(sOfferRewardAnswer.getImage())){
                    sOfferRewardAnswer.setImageList(sOfferRewardAnswer.getImage().split(","));
                }else {
                    String [] array = {};
                    sOfferRewardAnswer.setImageList(array);
                }

            }
        }else {
            for (SOfferRewardAnswer sOfferRewardAnswer : list) {
                //评论时间为多少时间前
                sOfferRewardAnswer.setTime(RelativeDateFormat.format(sOfferRewardAnswer.getAddTime()));
                //评论图片
                if (!StringUtil.isEmpty(sOfferRewardAnswer.getImage())){
                    sOfferRewardAnswer.setImageList(sOfferRewardAnswer.getImage().split(","));
                } else {
                    String [] array = {};
                    sOfferRewardAnswer.setImageList(array);
                }
            }
        }
        sOfferReward.setIsAdd(isAdd);

        map.clear();
        map.put("sOfferReward", sOfferReward);
        map.put("list", list);
        map.put("count", page.getPageTotal());
        return ObjectResult.build("1", "成功", map);
    }

    @Override
    public ObjectResult offerRewardanswer(XMLBean xmlBean,MultipartFile[] files) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        try {
            SOfferRewardAnswer sOfferRewardAnswer = new SOfferRewardAnswer();
            sOfferRewardAnswer.setRewardId(Integer.parseInt(xmlBean.getId()));
            sOfferRewardAnswer.setUserId(Long.parseLong(userId));
            sOfferRewardAnswer.setContent(xmlBean.getContent());
            sOfferRewardAnswer.setReport(0);
            sOfferRewardAnswer.setFabulous(0);
            sOfferRewardAnswer.setAddTime(new Date());
            sOfferRewardAnswer.setModifyTime(new Date());
            sOfferRewardAnswer.setIsDelete(0);



            //图片
            if(files.length>0){
                StringBuilder builder = new StringBuilder();
                List<String> list = FileUtil.upload(files, ConfigUtils.OFFERRWARD_ANSWER_URL);
                int i =1;
                for (String string:list){
                    if (i == files.length){
                        builder.append(ConfigUtils.FILE_URL+"image/offerewardAnswer/"+string);
                    }else {
                        builder.append(ConfigUtils.FILE_URL+"image/offerewardAnswer/"+string).append(",");
                    }
                }

                sOfferRewardAnswer.setImage(builder.toString());
            }

            sOfferRewardAnswerMapper.insertSelective(sOfferRewardAnswer);

            //修改回答次数
            SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));
            sUser.setAnswer(sUser.getAnswer()+1);
            sUserMapper.updateByPrimaryKeySelective(sUser);
        } catch (RuntimeException e) {
            ExceptionUtil.logError(e, log);
            return ObjectResult.build("0", "回答失败");
        }
        return ObjectResult.build("1", "回答成功");
    }

    @Override
    public ObjectResult addWrongTopic(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SWrongTopic sWrongTopic = sWrongTopicMapper
                .selectWrongTopicByRewadId(Long.parseLong(xmlBean.getId()));

        SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));
        String not_vip = sConfigMapper.select("not_vip");
        Integer count = sUserToWrongTopicMapper.selctCount(Long.parseLong(userId));
        if(count >= Integer.parseInt(not_vip) &&  sUser.getExpireTime().compareTo(new Date())<0){
            return ObjectResult.build("0","非会员最多可导入管理"+not_vip+"道错题");
        }

        try {
            //已有此错题
            if (sWrongTopic != null) {
                SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
                sUserToWrongTopic.setUserId(Long.parseLong(userId));
                sUserToWrongTopic.setTopicId(sWrongTopic.getId());
                sUserToWrongTopic.setIsDelete(0);
                sUserToWrongTopic.setAddTime(new Date());
                sUserToWrongTopic.setModify(new Date());
                SUserToWrongTopic select = sUserToWrongTopicMapper.select(sUserToWrongTopic);
                if (select != null) return ObjectResult.build("0","已加入错题本");
                sUserToWrongTopicMapper.insertSelective(sUserToWrongTopic);
            } else {//无此错题
                SOfferReward sOfferReward = sOfferRewardMapper
                        .selectByPrimaryKey(Long.parseLong(xmlBean.getId()));

                sWrongTopic = new SWrongTopic();
                if (StringUtil.isEmpty(sOfferReward.getImage())) {
                    sWrongTopic.setStem(sOfferReward.getContent());
                    sWrongTopic.setType(2);
                } else {
                    sWrongTopic.setStem(sOfferReward.getImage());
                    sWrongTopic.setOriginal(sOfferReward.getImage());
                    sWrongTopic.setType(1);
                }
                sWrongTopic.setSubjectId(sOfferReward.getSubjectId());
                sWrongTopic.setGradeId(sOfferReward.getGradeId());
                sWrongTopic.setRewadId(sOfferReward.getId());
                sWrongTopic.setAddTime(new Date());
                sWrongTopic.setUserId(sOfferReward.getUserId());

                sWrongTopic.setModifyTime(new Date());
                sWrongTopicMapper.insertSelective(sWrongTopic);

                SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
                sUserToWrongTopic.setUserId(Long.parseLong(userId));
                sUserToWrongTopic.setTopicId(sWrongTopic.getId());
                sUserToWrongTopic.setAddTime(new Date());
                sUserToWrongTopic.setModify(new Date());
                sUserToWrongTopicMapper.insertSelective(sUserToWrongTopic);

                //标签
                SSubject sSubject = sSubjectMapper.selectByPrimaryKey(sOfferReward.getSubjectId());
                Integer select = sLabelMapper.select(sSubject.getTitle());
                SWrongTopicLabel sWrongTopicLabel = new SWrongTopicLabel();
                sWrongTopicLabel.setLabelId(select);
                sWrongTopicLabel.setTopicId(sWrongTopic.getId());
                sWrongTopicLabelMapper.insertSelective(sWrongTopicLabel);
                sWrongTopicLabel.setLabelId(13);
                sWrongTopicLabelMapper.insertSelective(sWrongTopicLabel);

            }

        } catch (RuntimeException e) {
            ExceptionUtil.logError(e, log);
            return ObjectResult.build("0", "加入错题失败");
        }

        return ObjectResult.build("1", "加入错题成功");
    }

    @Override
    public ObjectResult offerRewardAdopt(XMLBean xmlBean) {
        try {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            SOfferReward sOfferReward = sOfferRewardMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getId()));
            if (!userId.equals(sOfferReward.getUserId().toString())){
                return ObjectResult.build("0", "非悬赏发布人");
            }

            SOfferRewardAnswer sOfferRewardAnswer = sOfferRewardAnswerMapper
                    .selectByPrimaryKey(Long.parseLong(xmlBean.getAnswerId()));
            if (sOfferRewardAnswer.getIsAdopt() == 1) {
                return ObjectResult.build("0", "已采纳该回答");
            }
            Integer count = sOfferRewardMapper.selectOfferRewardIsAdoptCount(Long.parseLong(xmlBean.getId()));
            if (count > 0) {
                return ObjectResult.build("0", "只能采纳一个回答");
            }

            SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

            if (sUser.getIntegral() < sOfferReward.getIntegral()) {
                return ObjectResult.build("0", "积分不足");
            }

            //修改回答为已采纳
            sOfferRewardAnswer.setIsAdopt(1);
            sOfferRewardAnswer.setModifyTime(new Date());
            sOfferRewardAnswerMapper.updateByPrimaryKeySelective(sOfferRewardAnswer);
            //修改悬赏为已解决
            sOfferReward.setStatus(1);
            sOfferReward.setModifyTime(new Date());
            sOfferRewardMapper.updateByPrimaryKeySelective(sOfferReward);
            //修改发布者积分
            sUser.setIntegral(sUser.getIntegral() - sOfferReward.getIntegral());
            sUserMapper.updateByPrimaryKeySelective(sUser);
            //修改回答者积分
            SUser user = sUserMapper.selectByPrimaryKey(sOfferRewardAnswer.getUserId());
            user.setIntegral(user.getIntegral() + sOfferReward.getIntegral());
            user.setAdopt(user.getAdopt()+1);
            sUserMapper.updateByPrimaryKeySelective(user);

        } catch (RuntimeException e) {
            ExceptionUtil.logError(e, log);
            return ObjectResult.build("0", "采纳回答失败");
        }

        return ObjectResult.build("1", "采纳回答成功");
    }

    @Override
    public ObjectResult offerRewardanswerFabulous(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SOfferRewardAnswerFabulous sOfferRewardAnswerFabulous = new SOfferRewardAnswerFabulous();
        sOfferRewardAnswerFabulous.setAnswerId(Long.parseLong(xmlBean.getAnswerId()));
        sOfferRewardAnswerFabulous.setUserId(Long.parseLong(userId));
        SOfferRewardAnswerFabulous select = sOfferRewardAnswerFabulousMapper.select(sOfferRewardAnswerFabulous);

        SOfferRewardAnswer sOfferRewardAnswer = sOfferRewardAnswerMapper
                .selectByPrimaryKey(Long.parseLong(xmlBean.getAnswerId()));
        try {

            Integer count = 1;
            // 1 举报 2 点赞
            if ("1".equals(xmlBean.getType())) {
                //没有就添加，有则修改
                if (select == null) {
                    sOfferRewardAnswerFabulous.setIsReport(1);
                    sOfferRewardAnswerFabulousMapper.insertSelective(sOfferRewardAnswerFabulous);
                } else {
                    if (select.getIsReport()==1){
                        select.setIsReport(0);
                        count = -1;
                    }else {
                        select.setIsReport(1);
                    }
                    sOfferRewardAnswerFabulousMapper.update(select);
                }
                sOfferRewardAnswer.setReport(sOfferRewardAnswer.getReport() + count);
            }
            if ("2".equals(xmlBean.getType())) {
                //没有就添加，有则修改
                if (select == null) {
                    sOfferRewardAnswerFabulous.setIsFabulous(1);
                    sOfferRewardAnswerFabulousMapper.insertSelective(sOfferRewardAnswerFabulous);
                } else {
                    if (select.getIsFabulous()==1){
                        select.setIsFabulous(0);
                        count = -1;
                    }else {
                        select.setIsFabulous(1);
                    }
                    sOfferRewardAnswerFabulousMapper.update(select);
                }
                sOfferRewardAnswer.setFabulous(sOfferRewardAnswer.getFabulous() + count);
            }
            //修改举报与点赞数
            sOfferRewardAnswerMapper.updateByPrimaryKeySelective(sOfferRewardAnswer);
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","操作失败");
        }
        return ObjectResult.build("1","操作成功");
    }
}
